const app = getApp()

Page({
  data: {
    stats: {
      memoCount: 0,
      storageCount: 0,
      roomCount: 0
    },
    recentRooms: []
  },

  onLoad() {
    this.loadStats()
    this.loadRecentRooms()
  },

  onShow() {
    this.loadStats()
    this.loadRecentRooms()
  },

  // 加载统计信息
  async loadStats() {
    try {
      const currentRoomId = app.getCurrentRoomId()
      if (!currentRoomId) {
        return
      }

      // 获取备忘录数量
      const memoRes = await app.request({
        url: `/api/memo/items/${currentRoomId}`,
        method: 'GET'
      })
      
      // 获取暂存室数量
      const storageRes = await app.request({
        url: `/api/storage/items/${currentRoomId}`,
        method: 'GET'
      })

      // 获取房间数量（从本地存储）
      const recentRooms = wx.getStorageSync('recentRooms') || []
      
      this.setData({
        stats: {
          memoCount: memoRes.data ? memoRes.data.length : 0,
          storageCount: storageRes.data ? storageRes.data.length : 0,
          roomCount: recentRooms.length
        }
      })
    } catch (error) {
      console.error('加载统计信息失败:', error)
    }
  },

  // 加载最近访问的房间
  loadRecentRooms() {
    try {
      const recentRooms = wx.getStorageSync('recentRooms') || []
      const formattedRooms = recentRooms.slice(0, 5).map(room => ({
        ...room,
        lastVisit: this.formatTime(room.lastVisit)
      }))
      
      this.setData({
        recentRooms: formattedRooms
      })
    } catch (error) {
      console.error('加载最近房间失败:', error)
    }
  },

  // 进入备忘录
  goToMemo() {
    wx.switchTab({
      url: '/pages/memo/memo'
    })
  },

  // 进入暂存室
  goToStorage() {
    wx.switchTab({
      url: '/pages/storage/storage'
    })
  },

  // 进入房间
  enterRoom(e) {
    const roomId = e.currentTarget.dataset.roomId
    if (roomId) {
      app.setCurrentRoomId(roomId)
      wx.switchTab({
        url: '/pages/memo/memo'
      })
    }
  },

  // 格式化时间
  formatTime(timestamp) {
    const now = new Date()
    const time = new Date(timestamp)
    const diff = now - time
    
    if (diff < 60000) { // 1分钟内
      return '刚刚'
    } else if (diff < 3600000) { // 1小时内
      return `${Math.floor(diff / 60000)}分钟前`
    } else if (diff < 86400000) { // 1天内
      return `${Math.floor(diff / 3600000)}小时前`
    } else if (diff < 604800000) { // 1周内
      return `${Math.floor(diff / 86400000)}天前`
    } else {
      return time.toLocaleDateString()
    }
  }
})